/**
 * Copyright (C)  2011  chen wei hua.
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 2.0
 * or any later version published by the Free Software Foundation;
 * with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
 * A copy of the license is included in the section entitled "GNU Free Documentation License".
 */
package com.javaeye.common.util;

import java.util.Collection;
import java.util.Iterator;

public class DAOUtil {
	
	@SuppressWarnings("unchecked")
	public static void mergeDataSet(Collection dbSet, Collection pageSet, SameObjectable sameable) {
		for (Iterator i = dbSet.iterator(); i.hasNext();) { 
			Object element = i.next(); 
		    if (!contains(element, pageSet, sameable)) { 
		    	sameable.removeObject(i, element);
		        //i.remove(); 
		    } 
		}
		for (Object element : pageSet) {
			if (!contains(element, dbSet, sameable)) {
				sameable.addObject(element);
			} else {
				Object dbo = getSameObject(element, dbSet, sameable);
				sameable.setValues(dbo, element);
			}
		}

	}
	
	@SuppressWarnings("unchecked")
	private static boolean contains(Object element, Collection set, SameObjectable sameable) {
		for (Object o : set) {
			if (sameable.isSameObject(element, o)) {
				return true;
			}
		}
		return false;
	}
	
	@SuppressWarnings("unchecked")
	private static Object getSameObject(Object element, Collection set, SameObjectable sameable) {
		for (Object o : set) {
			if (sameable.isSameObject(element, o)) {
				return o;
			}
		}
		return null;
	}
	
	public interface SameObjectable {
		
		/**
		 * 用字段值判断两个对象是否是同一个对象
		 * @param o1
		 * @param o2
		 * @return
		 */
		public boolean isSameObject(Object o1, Object o2);
		
		/**
		 * 添加一个新对象
		 * @param o
		 */
		public void addObject(Object o);
		
		/**
		 * 从数据库中删除一个对象
		 * 如果是物理删除用i.remove()
		 * @param i
		 * @param o
		 */
		@SuppressWarnings("unchecked")
		public void removeObject(Iterator i, Object o);
		
		/**
		 * 更新数据库对象的值为画面上的值
		 * @param dbElement
		 * @param pageElement
		 */
		public void setValues(Object dbElement, Object pageElement);
	}
}
